package com.kly.chatter.api.application.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.kly.chatter.api.application.utils.DateWeekUtils;
import com.kly.chatter.db.dao.ChatterDashboardInfoDao;
import com.kly.chatter.db.dao.ChatterRatingDao;
import com.kly.chatter.db.entity.ChatterRatingEntity;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * chatter等级
 */
@Slf4j
@Component
public class ChatterRatingTask {


    @Resource
    private UserService userService;

    @Autowired
    private ChatterDashboardInfoDao chatterDashboardInfoDao;

    @Autowired
    private ChatterRatingDao chatterRatingDao;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();



    //每周三晚上23:59:59
//    @Scheduled(fixedDelay = 15000)
    @Scheduled(cron = "59 59 23 ? * WED")
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============ChatterRatingTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        //时间为：上周四-本周三
        List<Date> thisWeek = DateWeekUtils.getweek(0, new Date());
        List<Date> lastWeek = DateWeekUtils.getweek(-1, new Date());
        List<Date> weekDay = new ArrayList<>();
        weekDay.add(lastWeek.get(3));
        weekDay.add(lastWeek.get(4));
        weekDay.add(lastWeek.get(5));
        weekDay.add(lastWeek.get(6));
        weekDay.add(thisWeek.get(0));
        weekDay.add(thisWeek.get(1));
        weekDay.add(thisWeek.get(2));
        List<UserInfoDto> chatterList = RpcUtils.getResult(userService.getUserByUserType("1"));
        for (UserInfoDto chatter : chatterList) {
            int totalPPVCount = 0;
            int onlineDay = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            for (Date date : weekDay) {
                //判断当天是否在线
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                String dates = sdf1.format(date);
                Integer checkOnline = userService.checkOnline(chatter.getUserCode(), dates);
                if (checkOnline > 0) {
                    onlineDay = onlineDay + 1;
                    Integer dateInter = Integer.parseInt(sdf.format(date));
                    Integer pPVCount = chatterDashboardInfoDao.getPPVCount(chatter.getUserCode(), dateInter);
                    totalPPVCount = totalPPVCount + pPVCount;
                }
            }
            int avgPPVCount = totalPPVCount / 7;
            int chatterRating = getChatterRating(avgPPVCount, onlineDay);

            ChatterRatingEntity chatterRatingEntity=new ChatterRatingEntity();
            chatterRatingEntity.setChatterUserCode(chatter.getUserCode());
            chatterRatingEntity.setChatterRating(chatterRating);
            chatterRatingEntity.setStartDay(Integer.parseInt(sdf.format(weekDay.get(0))));
            chatterRatingEntity.setEndDay(Integer.parseInt(sdf.format(weekDay.get(6))));
            chatterRatingEntity.setPpvCount(avgPPVCount);
            chatterRatingEntity.setOnlineDay(onlineDay);
            chatterRatingDao.insert(chatterRatingEntity);
            userService.updateChatterRating(chatter.getUserCode(), chatterRating);
        }
    }

    /**
     * 等级判断
     * @param avgPPVCount
     * @param onlineDay
     * @return
     */
    private int getChatterRating(int avgPPVCount, int onlineDay) {
        //1.SS 2.S 3.A 4.B
        //  1. B级主播：不符合其他标准时，定位在B级
        //  2. A级主播：日均产出8个及以上ppv，且周出勤天数>=6天的chatter
        //  3. S级主播：日均产出15个及以上ppv，且周出勤天数>=6天的chatter
        //  4. SS级主播：日均产出30个及以上ppv，且周出勤天数>=6天的chatter
        //  5. 出勤：chatter当日有过登录/上线记录的，就算出勤
        int result = 0;
        if (avgPPVCount > 0 && onlineDay > 5) {
            if (avgPPVCount >= 30) {
                result = 1;
            } else if (avgPPVCount >= 15) {
                result = 2;
            } else if (avgPPVCount >= 8) {
                result = 3;
            } else {
                result = 4;
            }
        } else {
            result = 4;
        }
        return result;
    }
}
